import { defineStore } from 'pinia'
import { ref } from 'vue'

export interface ChatSession {
  id: string
  title: string
  lastMessage?: string
  createTime: number
}

export const useChatStore = defineStore('chat', () => {
  const sessions = ref<ChatSession[]>([])
  const currentSessionId = ref<string>('')

  // 创建新会话
  function createSession() {
    const newSession: ChatSession = {
      id: Date.now().toString(),
      title: '新会话',
      createTime: Date.now(),
    }
    sessions.value.unshift(newSession)
    currentSessionId.value = newSession.id
    return newSession
  }

  // 切换会话
  function switchSession(sessionId: string) {
    currentSessionId.value = sessionId
  }

  // 更新会话标题
  function updateSessionTitle(sessionId: string, title: string) {
    const session = sessions.value.find((s) => s.id === sessionId)
    if (session) {
      session.title = title
    }
  }

  // 更新最后一条消息
  function updateLastMessage(sessionId: string, message: string) {
    const session = sessions.value.find((s) => s.id === sessionId)
    if (session) {
      session.lastMessage = message
    }
  }

  return {
    sessions,
    currentSessionId,
    createSession,
    switchSession,
    updateSessionTitle,
    updateLastMessage,
  }
})
